﻿using AutomatedTestDataManagement.Models;
using System.Data;
using System.Linq;
using System.Web.Mvc;

namespace AutomatedTestDataManagement.Controllers
{
    public class PageController : Controller
    {
        private ApplicationTestDataEntities db = new ApplicationTestDataEntities();

        //
        // GET: /Page/

        public ActionResult Index()
        {
            return View(db.Pages.ToList());
        }

        //
        // GET: /Page/Details/5

        public ActionResult Details(int id = 0)
        {
            Page page = db.Pages.Find(id);
            if (page == null)
            {
                return HttpNotFound();
            }
            return View(page);
        }

        //
        // GET: /Page/Create
        /// <summary>
        /// If parent site Id is passed in, passes through for use after the post action
        /// </summary>
        /// <param name="id">id of the parent site</param>
        /// <returns></returns>
        public ActionResult Create(int id = 0)
        {
            if (id != 0) { ViewBag.SiteID = id; }
            return View();
        }

        //
        // POST: /Page/Create
        /// <summary>
        /// Responds to HTTPPost only
        /// </summary>
        /// <param name="page">page data</param>
        /// <returns>If site ID is present, returns to the site edit view, otherwise to the page index view</returns>
        [HttpPost]
        public ActionResult Create(Page page)
        {
            if (ModelState.IsValid)
            {
                db.Pages.Add(page);
                db.SaveChanges();

                if (Request.Form["SiteID"] != null)
                {
                    // Add the page to the site
                    SitesPage sitesPage = new SitesPage();
                    sitesPage.SiteID = System.Convert.ToInt32(Request.Form["SiteID"]);
                    sitesPage.PageID = page.PageID;

                    TryUpdateModel(sitesPage, new string[] { "SiteID", "PageID" });
                    if (ModelState.IsValid)
                    {
                        db.SitesPages.Add(sitesPage);
                        db.SaveChanges();
                        return RedirectToAction("Edit", "Site", new { id = Request.Form["SiteID"] });
                    }
                }

                return RedirectToAction("Index");
            }

            if (Request.Form["SiteID"] != null){ ViewBag.SiteID = Request.Form["SiteID"]; }
            return View(page);
        }

        //
        // GET: /Page/Edit/5
        /// <summary>
        /// Loads data for page edit. If siteID is present, this is passed through to the edit view
        /// </summary>
        /// <param name="id">The page ID</param>
        /// <param name="siteID">Parent Site ID</param>
        /// <returns>Page information</returns>
        public ActionResult Edit(int id = 0, int siteID = 0)
        {
            Page page = db.Pages.Find(id);
            if (page == null)
            {
                return HttpNotFound();
            }
            if (siteID != 0)
            {
                ViewBag.SiteID = siteID;
            }
            return View(page);
        }

        //
        // POST: /Page/Edit/5
        /// <summary>
        /// Responds to HTTPPost action only
        /// </summary>
        /// <param name="page">Page data</param>
        /// <returns>If parent siteID is present, redirects to the site edit view after saving edits. Otherwise redirects to page index view</returns>
        [HttpPost]
        public ActionResult Edit(Page page)
        {
            if (ModelState.IsValid)
            {
                db.Entry(page).State = EntityState.Modified;
                db.SaveChanges();

                if (Request.Form["SiteID"] != null)
                {
                    return RedirectToAction("Edit", "Site", new { id = Request.Form["SiteID"] });
                }
                return RedirectToAction("Index");
            }
            return View(page);
        }


        //
        // GET: /Page/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Page page = db.Pages.Find(id);
            if (page == null)
            {
                return HttpNotFound();
            }

            if (page.PagesFields.Count > 0)
            {
                ModelState.AddModelError("", "This page has fields. All linked fields must be removed before deleting");
            }

            if (page.SitesPages.Count > 0)
            {
                ModelState.AddModelError("", "This page is used by at least one site. It must be removed from all linked sites before deleting");
            }
            return View(page);
        }

        
        //
        // POST: /Page/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Page page = db.Pages.Find(id);
            db.Pages.Remove(page);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}